SlideShare a Scribd company logo
1 of 34
Download to read offline
Step by Step Guide
for building a simple
 Struts Application


                        1
Sang Shin
    sang.shin@sun.com
 www.javapassion.com/j2ee
Java™ Technology Evangelist
   Sun Microsystems, Inc.
                              2
Sample App We are
  going to build



                    3
Sample App
● Keld Hansen's submit application
● Things to do

     –   Creating ActionForm object
     –   Creating Action object
     –   Forwarding at either success or failure through
         configuration set in struts-config.xml file
     –   Input validation
     –   Internationalizaition
●   You can also build it using NetBeans

                                                           4
Steps to follow



                  5
Steps
1.Create development directory structure
2.Write web.xml
3.Write struts-config.xml
4.Write ActionForm classes
5.Write Action classes
6.Create ApplicationResource.properties
7.Write JSP pages
8.Build, deploy, and test the application

                                            6
Step 1: Create Development
    Directory Structure


                         7
Development Directory
Structure
●   Same development directory structure for
    any typical Web application
●   Ant build script should be written
    accordingly
●   If you are using NetBeans, the
    development directory structure is
    automatically created


                                               8
Step 2: Write web.xml
Deployment Descriptor


                        9
web.xml
●   Same structure as any other Web
    application
    –   ActionServlet is like any other servlet
    –   Servlet definition and mapping of ActionServlet
        needs to be specified in the web.xml
●   There are several Struts specific
    <init-param> elements
    –   Location of Struts configuration file
●   Struts tag libraries could be defined

                                                          10
Example: web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
3       <servlet>
4         <servlet-name>action</servlet-name>
5         <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
6         <init-param>
7             <param-name>config</param-name>
8             <param-value>/WEB-INF/struts-config.xml</param-value>
9         </init-param>
10        ...
11       </servlet>
12       <servlet-mapping>
13          <servlet-name>action</servlet-name>
14          <url-pattern>*.do</url-pattern>
15       </servlet-mapping>
                                                                                  11
Step 3: Write
struts-config.xml


                    12
struts-config.xml
●   Identify required input forms and then define
    them as <form-bean> elements
●   Identify required Action's and then define them
    as <action> elements within <action-mappings>
    element
    –   make sure same value of name attribute of <form-
        bean> is used as the value of name attribute of
        <action> element
    –   define if you want input validation
●   Decide view selection logic and specify them as
    <forward> element within <action> element
                                                       13
struts-config.xml: <form-beans>
1    <?xml version="1.0" encoding="UTF-8" ?>
2
3    <!DOCTYPE struts-config PUBLIC
4    "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
5    "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
6
7
8    <struts-config>
9      <form-beans>
10          <form-bean   name="submitForm"
11                       type="submit.SubmitForm"/>
12     </form-beans>




                                                                    14
struts-config.xml:
<action-mappings>
 1
 2 <!-- ==== Action Mapping Definitions ===============-->
 3    <action-mappings>
 4
 5       <action path="/submit"
 6             type="submit.SubmitAction"
 7             name="submitForm"
 8             input="/submit.jsp"
 9             scope="request"
 10              validate="true">
 11         <forward name="success" path="/submit.jsp"/>
 12         <forward name="failure" path="/submit.jsp"/>
 13       </action>
 14
 15    </action-mappings>


                                                             15
Step 4: Write
ActionForm classes


                     16
ActionForm Class
●   Extend org.apache.struts.action.ActionForm
    class
●   Decide set of properties that reflect the input
    form
●   Write getter and setter methods for each
    property
●   Write validate() method if input validation is
    desired


                                                  17
Write ActionForm class
1    package submit;
2
3    import javax.servlet.http.HttpServletRequest;
4    import org.apache.struts.action.*;
5
6    public final class SubmitForm extends ActionForm {
7
8      /* Last Name */
9      private String lastName = "Hansen"; // default value
10     public String getLastName() {
11       return (this.lastName);
12     }
13     public void setLastName(String lastName) {
14       this.lastName = lastName;
15     }
16
17     /* Address */
18     private String address = null;
19     public String getAddress() {
20       return (this.address);
21     }
22     public void setAddress(String address) {
23       this.address = address;
24     }                                                      18
Write validate() method
1    public final class SubmitForm extends ActionForm {
2
3    ...
4      public ActionErrors validate(ActionMapping mapping,
5         HttpServletRequest request) {
6
7      ...
8
9       // Check for mandatory data
10       ActionErrors errors = new ActionErrors();
11       if (lastName == null || lastName.equals("")) {
12         errors.add("Last Name", new ActionError("error.lastName"));
13       }
14       if (address == null || address.equals("")) {
15         errors.add("Address", new ActionError("error.address"));
16       }
17       if (sex == null || sex.equals("")) {
18         errors.add("Sex", new ActionError("error.sex"));
19       }
20       if (age == null || age.equals("")) {
21         errors.add("Age", new ActionError("error.age"));
22       }
23       return errors;
24     }                                                                 19
Step 5: Write
Action classes


                 20
Action Classes
●   Extend org.apache.struts.action.Action class
●   Handle the request
    –   Decide what kind of server-side Model objects
        (EJB, JDO, etc.) can be invoked
●   Based on the outcome, select the next view




                                                        21
Example: Action Class
1 package submit;
2
3 import javax.servlet.http.*;
4 import org.apache.struts.action.*;
5
6 public final class SubmitAction extends Action {
7
8    public ActionForward execute(ActionMapping mapping,
9                                 ActionForm form,
10                                HttpServletRequest request,
11                                HttpServletResponse response) {
12
13      SubmitForm f = (SubmitForm) form; // get the form bean
14      // and take the last name value
15      String lastName = f.getLastName();
16      // Translate the name to upper case
17      //and save it in the request object
18      request.setAttribute("lastName", lastName.toUpperCase());
19
20      // Forward control to the specified success target
21      return (mapping.findForward("success"));
22    }
23 }                                                                22
Step 6: Create
ApplicationResource.properties
    and Configure web.xml
          accordingly


                                 23
Resource file
●   Create resource file for default locale
●   Create resource files for other locales




                                              24
Example:
ApplicationResource.properties
1   errors.header=<h4>Validation Error(s)</h4><ul>
2   errors.footer=</ul><hr>
3
4   error.lastName=<li>Enter your last name
5   error.address=<li>Enter your address
6   error.sex=<li>Enter your sex
7   error.age=<li>Enter your age




                                                     25
Step 7: Write JSP pages


                          26
JSP Pages
●   Write one JSP page for each view
●   Use Struts tags for
    –   Handing HTML input forms
    –   Writing out messages




                                       27
Example: submit.jsp
1    <%@ page language="java" %>
2    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
3    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
4    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
5
6    <html>
7    <head><title>Submit example</title></head>
8    <body>
9
10    <h3>Example Submit Page</h3>
11
12    <html:errors/>
13
14    <html:form action="submit.do">
15    Last Name: <html:text property="lastName"/><br>
16    Address: <html:textarea property="address"/><br>
17    Sex:     <html:radio property="sex" value="M"/>Male
18          <html:radio property="sex" value="F"/>Female<br>
19    Married: <html:checkbox property="married"/><br>
20    Age:     <html:select property="age">
21            <html:option value="a">0-19</html:option>
22            <html:option value="b">20-49</html:option>
23            <html:option value="c">50-</html:option>
24          </html:select><br>
25          <html:submit/>
                                                                    28
26    </html:form>
Example: submit.jsp
1    <logic:present name="lastName" scope="request">
2    Hello
3    <logic:equal name="submitForm" property="age" value="a">
4     young
5    </logic:equal>
6    <logic:equal name="submitForm" property="age" value="c">
7     old
8    </logic:equal>
9    <bean:write name="lastName" scope="request"/>
10    </logic:present>
11
12    </body>
13    </html>




                                                                29
Step 8: Build, Deploy,
and Test Application


                         30
Accessing Web Application




                            31
Accessing Web Application




                            32
Accessing Web Application




                            33
Passion!


           34

More Related Content

What's hot

React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0Matt Raible
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersDavid Rodenas
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and ReduxThom Nichols
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and reduxCuong Ho
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max PetruckMaksym Petruk
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes senseEldar Djafarov
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and ReduxGlib Kechyn
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2DreamLab
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingNatasha Murashev
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and EasybIakiv Kramarenko
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15Rob Gietema
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 

What's hot (20)

React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and Redux
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and Easyb
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 

Viewers also liked

Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts weili_at_slideshare
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Applicationelliando dias
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworksMukesh Kumar
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Building Enterprise Application with J2EE
Building Enterprise Application with J2EEBuilding Enterprise Application with J2EE
Building Enterprise Application with J2EECalance
 

Viewers also liked (18)

Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Introduction to Struts 2
Introduction to Struts 2Introduction to Struts 2
Introduction to Struts 2
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
Frameworks in java
Frameworks in javaFrameworks in java
Frameworks in java
 
Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Application
 
Struts Basics
Struts BasicsStruts Basics
Struts Basics
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworks
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Building Enterprise Application with J2EE
Building Enterprise Application with J2EEBuilding Enterprise Application with J2EE
Building Enterprise Application with J2EE
 

Similar to Step by Step Guide to Building a Simple Struts Application

Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Rati Manandhar
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011Arun Gupta
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applicationselliando dias
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorialOPENLANE
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...varunsunny21
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksmwbrooks
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with StripesSamuel Santos
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integrationwhabicht
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauSpiffy
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Michael Plöd
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 

Similar to Step by Step Guide to Building a Simple Struts Application (20)

Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
Jsf
JsfJsf
Jsf
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorial
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Struts Overview
Struts OverviewStruts Overview
Struts Overview
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorks
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with Stripes
 
Web based development
Web based developmentWeb based development
Web based development
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integration
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 

More from Syed Shahul

Beginning java and flex migrating java, spring, hibernate, and maven develop...
Beginning java and flex  migrating java, spring, hibernate, and maven develop...Beginning java and flex  migrating java, spring, hibernate, and maven develop...
Beginning java and flex migrating java, spring, hibernate, and maven develop...Syed Shahul
 
Struts 2 And Spring Frameworks Together
Struts 2 And Spring Frameworks TogetherStruts 2 And Spring Frameworks Together
Struts 2 And Spring Frameworks TogetherSyed Shahul
 
Manning Struts 2 In Action
Manning Struts 2 In ActionManning Struts 2 In Action
Manning Struts 2 In ActionSyed Shahul
 
Sahih Bukhari - Tamil
Sahih Bukhari - TamilSahih Bukhari - Tamil
Sahih Bukhari - TamilSyed Shahul
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsSyed Shahul
 
Hibernate Reference
Hibernate ReferenceHibernate Reference
Hibernate ReferenceSyed Shahul
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample ChapterSyed Shahul
 
Spring Reference
Spring ReferenceSpring Reference
Spring ReferenceSyed Shahul
 

More from Syed Shahul (14)

Beginning java and flex migrating java, spring, hibernate, and maven develop...
Beginning java and flex  migrating java, spring, hibernate, and maven develop...Beginning java and flex  migrating java, spring, hibernate, and maven develop...
Beginning java and flex migrating java, spring, hibernate, and maven develop...
 
Struts 2 And Spring Frameworks Together
Struts 2 And Spring Frameworks TogetherStruts 2 And Spring Frameworks Together
Struts 2 And Spring Frameworks Together
 
Manning Struts 2 In Action
Manning Struts 2 In ActionManning Struts 2 In Action
Manning Struts 2 In Action
 
Sahih Bukhari - Tamil
Sahih Bukhari - TamilSahih Bukhari - Tamil
Sahih Bukhari - Tamil
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Struts Live
Struts LiveStruts Live
Struts Live
 
Struts Intro
Struts IntroStruts Intro
Struts Intro
 
Hibernate Reference
Hibernate ReferenceHibernate Reference
Hibernate Reference
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
 
Spring Reference
Spring ReferenceSpring Reference
Spring Reference
 
Jamon 22
Jamon 22Jamon 22
Jamon 22
 
Do U Know Him
Do U Know HimDo U Know Him
Do U Know Him
 
Hot Chocolate
Hot ChocolateHot Chocolate
Hot Chocolate
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Step by Step Guide to Building a Simple Struts Application

  • 1. Step by Step Guide for building a simple Struts Application 1
  • 2. Sang Shin sang.shin@sun.com www.javapassion.com/j2ee Java™ Technology Evangelist Sun Microsystems, Inc. 2
  • 3. Sample App We are going to build 3
  • 4. Sample App ● Keld Hansen's submit application ● Things to do – Creating ActionForm object – Creating Action object – Forwarding at either success or failure through configuration set in struts-config.xml file – Input validation – Internationalizaition ● You can also build it using NetBeans 4
  • 6. Steps 1.Create development directory structure 2.Write web.xml 3.Write struts-config.xml 4.Write ActionForm classes 5.Write Action classes 6.Create ApplicationResource.properties 7.Write JSP pages 8.Build, deploy, and test the application 6
  • 7. Step 1: Create Development Directory Structure 7
  • 8. Development Directory Structure ● Same development directory structure for any typical Web application ● Ant build script should be written accordingly ● If you are using NetBeans, the development directory structure is automatically created 8
  • 9. Step 2: Write web.xml Deployment Descriptor 9
  • 10. web.xml ● Same structure as any other Web application – ActionServlet is like any other servlet – Servlet definition and mapping of ActionServlet needs to be specified in the web.xml ● There are several Struts specific <init-param> elements – Location of Struts configuration file ● Struts tag libraries could be defined 10
  • 11. Example: web.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 3 <servlet> 4 <servlet-name>action</servlet-name> 5 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> 6 <init-param> 7 <param-name>config</param-name> 8 <param-value>/WEB-INF/struts-config.xml</param-value> 9 </init-param> 10 ... 11 </servlet> 12 <servlet-mapping> 13 <servlet-name>action</servlet-name> 14 <url-pattern>*.do</url-pattern> 15 </servlet-mapping> 11
  • 13. struts-config.xml ● Identify required input forms and then define them as <form-bean> elements ● Identify required Action's and then define them as <action> elements within <action-mappings> element – make sure same value of name attribute of <form- bean> is used as the value of name attribute of <action> element – define if you want input validation ● Decide view selection logic and specify them as <forward> element within <action> element 13
  • 14. struts-config.xml: <form-beans> 1 <?xml version="1.0" encoding="UTF-8" ?> 2 3 <!DOCTYPE struts-config PUBLIC 4 "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" 5 "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> 6 7 8 <struts-config> 9 <form-beans> 10 <form-bean name="submitForm" 11 type="submit.SubmitForm"/> 12 </form-beans> 14
  • 15. struts-config.xml: <action-mappings> 1 2 <!-- ==== Action Mapping Definitions ===============--> 3 <action-mappings> 4 5 <action path="/submit" 6 type="submit.SubmitAction" 7 name="submitForm" 8 input="/submit.jsp" 9 scope="request" 10 validate="true"> 11 <forward name="success" path="/submit.jsp"/> 12 <forward name="failure" path="/submit.jsp"/> 13 </action> 14 15 </action-mappings> 15
  • 17. ActionForm Class ● Extend org.apache.struts.action.ActionForm class ● Decide set of properties that reflect the input form ● Write getter and setter methods for each property ● Write validate() method if input validation is desired 17
  • 18. Write ActionForm class 1 package submit; 2 3 import javax.servlet.http.HttpServletRequest; 4 import org.apache.struts.action.*; 5 6 public final class SubmitForm extends ActionForm { 7 8 /* Last Name */ 9 private String lastName = "Hansen"; // default value 10 public String getLastName() { 11 return (this.lastName); 12 } 13 public void setLastName(String lastName) { 14 this.lastName = lastName; 15 } 16 17 /* Address */ 18 private String address = null; 19 public String getAddress() { 20 return (this.address); 21 } 22 public void setAddress(String address) { 23 this.address = address; 24 } 18
  • 19. Write validate() method 1 public final class SubmitForm extends ActionForm { 2 3 ... 4 public ActionErrors validate(ActionMapping mapping, 5 HttpServletRequest request) { 6 7 ... 8 9 // Check for mandatory data 10 ActionErrors errors = new ActionErrors(); 11 if (lastName == null || lastName.equals("")) { 12 errors.add("Last Name", new ActionError("error.lastName")); 13 } 14 if (address == null || address.equals("")) { 15 errors.add("Address", new ActionError("error.address")); 16 } 17 if (sex == null || sex.equals("")) { 18 errors.add("Sex", new ActionError("error.sex")); 19 } 20 if (age == null || age.equals("")) { 21 errors.add("Age", new ActionError("error.age")); 22 } 23 return errors; 24 } 19
  • 20. Step 5: Write Action classes 20
  • 21. Action Classes ● Extend org.apache.struts.action.Action class ● Handle the request – Decide what kind of server-side Model objects (EJB, JDO, etc.) can be invoked ● Based on the outcome, select the next view 21
  • 22. Example: Action Class 1 package submit; 2 3 import javax.servlet.http.*; 4 import org.apache.struts.action.*; 5 6 public final class SubmitAction extends Action { 7 8 public ActionForward execute(ActionMapping mapping, 9 ActionForm form, 10 HttpServletRequest request, 11 HttpServletResponse response) { 12 13 SubmitForm f = (SubmitForm) form; // get the form bean 14 // and take the last name value 15 String lastName = f.getLastName(); 16 // Translate the name to upper case 17 //and save it in the request object 18 request.setAttribute("lastName", lastName.toUpperCase()); 19 20 // Forward control to the specified success target 21 return (mapping.findForward("success")); 22 } 23 } 22
  • 23. Step 6: Create ApplicationResource.properties and Configure web.xml accordingly 23
  • 24. Resource file ● Create resource file for default locale ● Create resource files for other locales 24
  • 25. Example: ApplicationResource.properties 1 errors.header=<h4>Validation Error(s)</h4><ul> 2 errors.footer=</ul><hr> 3 4 error.lastName=<li>Enter your last name 5 error.address=<li>Enter your address 6 error.sex=<li>Enter your sex 7 error.age=<li>Enter your age 25
  • 26. Step 7: Write JSP pages 26
  • 27. JSP Pages ● Write one JSP page for each view ● Use Struts tags for – Handing HTML input forms – Writing out messages 27
  • 28. Example: submit.jsp 1 <%@ page language="java" %> 2 <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 3 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> 4 <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 5 6 <html> 7 <head><title>Submit example</title></head> 8 <body> 9 10 <h3>Example Submit Page</h3> 11 12 <html:errors/> 13 14 <html:form action="submit.do"> 15 Last Name: <html:text property="lastName"/><br> 16 Address: <html:textarea property="address"/><br> 17 Sex: <html:radio property="sex" value="M"/>Male 18 <html:radio property="sex" value="F"/>Female<br> 19 Married: <html:checkbox property="married"/><br> 20 Age: <html:select property="age"> 21 <html:option value="a">0-19</html:option> 22 <html:option value="b">20-49</html:option> 23 <html:option value="c">50-</html:option> 24 </html:select><br> 25 <html:submit/> 28 26 </html:form>
  • 29. Example: submit.jsp 1 <logic:present name="lastName" scope="request"> 2 Hello 3 <logic:equal name="submitForm" property="age" value="a"> 4 young 5 </logic:equal> 6 <logic:equal name="submitForm" property="age" value="c"> 7 old 8 </logic:equal> 9 <bean:write name="lastName" scope="request"/> 10 </logic:present> 11 12 </body> 13 </html> 29
  • 30. Step 8: Build, Deploy, and Test Application 30
  • 34. Passion! 34